package com.uni.crawl.common.util.crawl;

import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * URL工具
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UrlUtils {

    /**
     * 格式化文本，使用 {varName} 占位<br>
     * map = {a: "aValue", b: "bValue"} format("{a} and {b}", map) ---=》 aValue and bValue
     */
    public static String replaceParam(String url, Map<String, Object> paramMap) {
        return StrUtil.format(url, paramMap, true);
    }

    public static List<String> getParamList(String url) {
        List<String> list = new ArrayList<>();
        if (StrUtil.isBlank(url)) {
            return list;
        }

        Pattern p = Pattern.compile("\\{(.*?)}");
        Matcher m = p.matcher(url);
        while (m.find()) {
            list.add(m.group(1));
        }
        return list;
    }
}
